/**
 * 校验token是否有效
 */
const jwt = require('jsonwebtoken')
const auth = require('basic-auth')
const { secretKey } = require('@config').security
const { AuthFailedException } = require('@core/http-exception.js')
class Auth {
  constructor (level = 1) {
    this.level = level
    Auth.USER = 8
    Auth.ADMIN = 16
    Auth.SUPER_ADMIN = 32
  }
  // 权限控制
  get controllerAuthApi () {
    return async (ctx, next) => {
      const userToken = auth(ctx.req)
      if (!userToken || !userToken.name) {
        throw new AuthFailedException('未携带token')
      }
      let decoded
      try {
        decoded = jwt.verify(userToken.name, secretKey)
      } catch (err) {
        if (err.name === 'JsonWebTokenError') {
          throw new AuthFailedException(`token不合法: ${err.name} ${err.message}`)
        } else {
          throw new AuthFailedException(`遇到错误: ${err.name} ${err.message}`)
        }
      }
      if (decoded.scope < this.level) {
        throw new AuthFailedException('无权限访问接口')
      }
      console.log(decoded);
      ctx.auth = {
        uid: decoded.uid,
        scope: decoded.scope
      }
      await next()
    }
  }
  // 校验token
  static verifyToken (token) {
    // 解析你的token
    let decoded
    try {
      decoded = jwt.verify(token, secretKey)
      return {
        token: true,
        uid: decoded.uid,
        scope: decoded.scope
      }
    } catch (err) {
      if (err.name === 'JsonWebTokenError') {
        throw new AuthFailedException(`token不合法: ${err.name} ${err.message}`)
      } else {
        throw new AuthFailedException(`遇到错误: ${err.name} ${err.message}`)
      }
    }
  }
}

module.exports = {
  Auth
}